package com.littcore.saap.core.web.filter;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import com.littcore.common.BeanManager;
import com.littcore.common.Utility;
import com.littcore.exception.BusiException;
import com.littcore.saap.common.session.SessionManager;
import com.littcore.saap.common.vo.LoginUserVo;
import com.littcore.saap.system.biz.IUserBizService;
import com.littcore.saap.system.dao.UserInfoDao;
import com.littcore.saap.system.dao.UserStateDao;
import com.littcore.saap.system.po.UserInfo;
import com.littcore.saap.system.po.UserState;
import com.littcore.saap.system.vo.UserInfoVo;
import com.littcore.saap.system.vo.UserStateVo;
import com.littcore.shield.security.SecurityContext;
import com.littcore.shield.security.SecurityContextHolder;
import com.littcore.util.BeanCopier;
import com.littcore.web.util.WebUtils;


public class WechatAutoLoginFilter extends OncePerRequestFilter implements Filter{
  
  private static final Logger logger = LoggerFactory.getLogger(WechatAutoLoginFilter.class); 


  
  /* (non-Javadoc)
   * @see org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
   */
  @Override
  protected void doFilterInternal(HttpServletRequest request,
      HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {
      String uri=request.getRequestURI();
      if(!uri.contains("/rest/")){
          super.doFilter(request, response, filterChain);
          return;
      }
      if("OPTIONS".equalsIgnoreCase(request.getMethod()))
      {
        injectHeader(response);
        response.setStatus(200);
        return;
      }
      logger.debug("rest try to login:"+uri);
      int userId=Utility.parseInt(request.getHeader("token"));
      if(userId==0){
          userId=Utility.parseInt(request.getParameter("token"));
      }
      if(userId==0){
          throw new BusiException("token is null");
      }
      String loginIp =  WebUtils.getRemoteIp(request); 
      SessionManager sessionManager=BeanManager.getBean("sessionManager", SessionManager.class);
      LoginUserVo currentLoginVo=(LoginUserVo)sessionManager.getSession(String.valueOf(userId));
  
      
      UserInfoDao userInfoDao= BeanManager.getBean("userInfoDao", UserInfoDao.class);
      UserStateDao userStateDao=BeanManager.getBean("userStateDao",UserStateDao.class);
      IUserBizService userBizService=BeanManager.getBean("userBizService",IUserBizService.class);
      
      
      UserInfo userInfo=userInfoDao.load(userId);
      UserState userState=userStateDao.load(userId);
      String sessionId=request.getRequestedSessionId();
     
      if(currentLoginVo==null){
          currentLoginVo =new LoginUserVo(BeanCopier.copy(userInfo, UserInfoVo.class), BeanCopier.copy(userState,UserStateVo.class), loginIp);
          userBizService.initDefaultPermission(currentLoginVo);
          
          //初始化租户权限
          userBizService.initLoginUserTenant(currentLoginVo);  
          sessionManager.cacheSession(sessionId, currentLoginVo, request);
      }
      //将登录信息存入安全管理容器并绑定到当前线程
      SecurityContext context = SecurityContextHolder.getContext();
      if(context==null)
        context = new SecurityContext();
      context.setLoginVo(currentLoginVo);       
        SecurityContextHolder.setContext(context); 

        HttpSession session = request.getSession();
        session.setAttribute("SESSION_USER", currentLoginVo);
        
        injectHeader(response);

        super.doFilter(request, response, filterChain);
  }

  /**
   * @param response
   */
  private void injectHeader(HttpServletResponse response)
  {
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "POST, GET, PUT,OPTIONS");
    response.setHeader("Access-Control-Allow-Credentials", "true");  //cookie信息、HTTP授权信息、客户端的SSL证书等发送到服务器端
    //response.addHeader("Access-Control-Allow-Headers", "accept,");
    response.addHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,Authorization");
    response.addHeader("P3P","CP=CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR");
  }
  
  

}
